﻿using System.Transactions;
using Api.Attributes;
using Microsoft.AspNetCore.Http.Features;
using SqlSugar;

namespace Api.Middleware
{
    /// <summary>
    /// 全局统一事务处理
    /// </summary>
    public class TransactionMiddleware
    {
        #region Ioc
        private readonly RequestDelegate _next;
        private readonly ISqlSugarClient _DB;

        public TransactionMiddleware(RequestDelegate next, ISqlSugarClient dB)
        {
            _next = next;
            _DB = dB;
        }
        #endregion

        #region InvokeAsync
        public async Task InvokeAsync(HttpContext context)
        {
            var endpoint = context.Features.Get<IEndpointFeature>()?.Endpoint;

            if (endpoint.IsNotEmpty() && endpoint.Metadata.GetMetadata<NotTranscationAttribute>().IsNotEmpty())
            {
                //如果有特性，则跳过此中间件
                await _next(context);
            }
            else
            {
                using (TransactionScope ts = new(TransactionScopeAsyncFlowOption.Enabled))
                {
                    await _next(context);
                    ts.Complete();
                }

                //try
                //{
                //    _DB.AsTenant().BeginTran();
                //    await _next(context);
                //    _DB.AsTenant().CommitTran();
                //}
                //catch
                //{
                //    _DB.AsTenant().RollbackTran();
                //    throw;
                //}
            }
        }
        #endregion
    }

    #region 扩展方法
    public static class TransactionMiddlewareExt
    {
        public static IApplicationBuilder UseTransaction(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<TransactionMiddleware>();
        }
    }
    #endregion
}
